<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--机构名称数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
              v-model="name"
              :placeholder="$t('equipment.companyInput')"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
              ref="tree"
              :data="deptOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              :highlight-current="true"
              default-expand-all
              @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
          <el-form-item :label="$t('role.userName')" prop="userName">
            <el-input
                v-model="queryParams.userName"
                :placeholder="$t('role.userNameInput')"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item :label="$t('role.phone')" prop="phone">
            <el-input
                v-model="queryParams.phone"
                :placeholder="$t('role.phoneInput')"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item :label="$t('program.status')" prop="status">
            <el-select
                v-model="queryParams.status"
                :placeholder="$t('role.userStatus')"
                clearable
                size="small"
                style="width: 240px"
            >
              <el-option
                  v-for="dict in statusOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('elButton.establishTime')">
            <el-date-picker
                v-model="dateRange"
                size="small"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                :start-placeholder="$t('elButton.startTime')"
                :end-placeholder="$t('elButton.endTime')"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{
                $t('elButton.search')
              }}
            </el-button>
            <el-button icon="el-icon-refresh-right" size="mini" @click="resetQuery">{{
                $t('elButton.reset')
              }}
            </el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                v-hasPerm="['user_add']"
                type="primary"
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
            >{{ $t('elButton.add') }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                v-hasPerm="['user_edit']"
                type="success"
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleEdit"
            >{{ $t('elButton.change') }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                v-hasPerm="['user_del']"
                type="danger"
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDel"
            >{{ $t('elButton.delete') }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                v-hasPerm="['user_import']"
                type="info"
                icon="el-icon-upload2"
                size="mini"
                @click="handleImport"
            >{{ $t('elButton.import') }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                v-hasPerm="['user_export']"
                type="warning"
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
            >{{ $t('elButton.export') }}
            </el-button>
          </el-col>

          <div class="top-right-btn">
            <el-tooltip class="item" effect="dark" :content="$t('elButton.refresh')" placement="top">
              <el-button size="mini" circle icon="el-icon-refresh" @click="handleQuery"/>
            </el-tooltip>
            <el-tooltip class="item" effect="dark"
                        :content="showSearch ? $t('elButton.hideSearch') : $t('elButton.showSearch')" placement="top"
            >
              <el-button size="mini" circle icon="el-icon-search" @click="showSearch=!showSearch"/>
            </el-tooltip>
          </div>
        </el-row>

        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="45" align="center"/>
          <el-table-column :label="$t('role.userNumber')" align="center" prop="id"/>
          <el-table-column :label="$t('role.nickName')" align="center" prop="nickName" :show-overflow-tooltip="true"/>
          <el-table-column :label="$t('role.userName')" align="center" prop="userName" :show-overflow-tooltip="true"/>
          <el-table-column :label="$t('equipment.company')" align="center" prop="deptName"
                           :show-overflow-tooltip="true"
          />
          <el-table-column :label="$t('role.phone')" align="center" prop="phone" width="120"/>
          <el-table-column :label="$t('program.status')" align="center">
            <template slot-scope="scope">
              <el-switch
                  v-model="scope.row.status"
                  active-value="0"
                  inactive-value="1"
                  @change="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column :label="$t('elButton.establishTime')" align="center" prop="createTime" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('equipment.control')" align="center" width="180"
                           class-name="small-padding fixed-width" fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                  v-hasPerm="['user_edit']"
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleEdit(scope.row)"
              >{{ $t('elButton.change') }}
              </el-button>
              <el-button
                  v-if="scope.row.id !== 1"
                  v-hasPerm="['user_del']"
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDel(scope.row)"
              >{{ $t('elButton.delete') }}
              </el-button>
              <el-button
                  v-hasPerm="['user_reset']"
                  size="mini"
                  type="text"
                  icon="el-icon-key"
                  @click="handleResetPwd(scope.row)"
              >{{ $t('elButton.reset') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.current"
            :limit.sync="queryParams.size"
            @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="720px" :modal-append-to-body="true" :append-to-body="true"
               :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('role.nickName')" prop="nickName">
              <el-input v-model="form.nickName" :placeholder="$t('role.nickNameInput')"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('role.deptId')" prop="deptId">
              <treeselect  @input="inputSelect" v-model="form.deptId" :options="deptOptions" :default-expand-level="2"
                          :normalizer="normalizer" :placeholder="$t('role.deptIdSelect')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('role.phone')">
              <el-input v-model="form.phone" :placeholder="$t('role.phoneInput')" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.id == undefined" :label="$t('role.password')" prop="password">
              <el-input v-model="form.password" :placeholder="$t('role.passwordInput')" type="password" show-password/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('mechanism.mailbox')" >
              <el-input v-model="form.email" :placeholder="$t('mechanism.mailboxInput')" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('role.userName')" prop="userName">
              <el-input v-model="form.userName" :placeholder="$t('role.userNameInput')"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('role.sex')">
              <el-select v-model="form.sex" :placeholder="$t('role.choose')">
                <el-option
                    v-for="dict in sexOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('program.status')">
              <el-radio-group v-model="form.status">
                <el-radio
                    v-for="dict in statusOptions"
                    :key="dict.value"
                    :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="$t('role.role')"  prop="roles" >
              <el-select  v-model="form.roles" multiple :placeholder="$t('role.choose')">
                <el-option
                    v-for="item in roleOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                    :disabled="item.status == 1"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('equipment.remarks')">
              <el-input v-model="form.remarks" type="textarea" :placeholder="$t('equipment.remarksInput')"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('submitText') }}</el-button>
        <el-button @click="cancel">{{ $t('cancelText') }}</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" :modal-append-to-body="true"
               :append-to-body="true"
    >
      <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-error="handleFileError"
          :auto-upload="false"
          drag
      >
        <i class="el-icon-upload"/>
        <div class="el-upload__text">
          {{ $t('edition.uploadDrop') }}<em>{{ $t('edition.uploadClick') }}</em>
        </div>
        <div slot="tip" class="el-upload__tip">
          <el-checkbox v-model="upload.updateSupport"/>
          {{ $t('edition.isUpdate') }}
          <el-link type="info" style="font-size:12px" @click="importTemplate">{{
              $t('edition.downLoadTemplate')
            }}
          </el-link>
        </div>
        <div slot="tip" class="el-upload__tip" style="color:red">{{ $t('edition.importWarning') }}</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">{{ $t('submitText') }}</el-button>
        <el-button @click="upload.open = false">{{ $t('cancelText') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="$t('profile.resetPwd')" :visible.sync="resetStatus" width="20%" :modal-append-to-body="true"
               :append-to-body="true" :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('profile.newPassword')" prop="newPassword">
              <el-input v-model="form.newPassword" :placeholder="$t('profile.newPasswordInput')"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleResetPwdSure">{{ $t('submitText') }}</el-button>
        <el-button @click="resetStatus=false">{{ $t('cancelText') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser,
  getUser,
  delUser,
  addUser,
  editUser,
  exportUser,
  resetPwd,
  changeStatus,
  importTemplate
} from '@/api/system/user'
import { getAccessToken } from '@/data/user'
import { deptTree } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'User',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      resetStatus: false,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: '',
      resetId: '',
      // 机构名称树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      showStatus: false,
      // 机构名称
      name: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 性别状态字典
      sexOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getAccessToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/system/user/importUser'
      },
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        userName: undefined,
        phone: undefined,
        status: undefined,
        deptId: undefined
      },
      // 显示搜索条件
      showSearch: true,
      // 表单校验
      rules: {
        userName: [
          { required: true, message: this.$t('userNameEmpty'), trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: this.$t('role.newPasswordInput'), trigger: 'blur' },
          { min: 6, message: this.$t('lessPassword'), trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: this.$t('role.nickNameEmpty'), trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: this.$t('role.deptIdEmpty'), trigger: 'blur' }
        ],
        roles: [
          { required: true,message: this.$t('role.roleInput'), trigger: 'change' }
        ],
        password: [
          { required: true, message: this.$t('passwordEmpty'), trigger: 'blur' },
          { min: 6, message: this.$t('lessPassword'), trigger: 'blur' }
        ],
        email: [
          { required: true,  message: this.$t('profile.emailEmpty'), trigger: 'blur' },
          {
            type: 'email',
            message: this.$t('profile.emailRight'),
            trigger: ['blur', 'change']
          }
        ],
        // phone: [
        //   {
        //     pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        //     message: this.$t('profile.phoneRight'),
        //     trigger: 'blur'
        //   }
        // ]
      }
    }
  },
  watch: {
    // 根据名称筛选机构名称树
    name(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    this.getDeptTree()
    this.getDicts('status').then(response => {
      this.statusOptions = response.data
    })
    this.getDicts('user_sex').then(response => {
      this.sexOptions = response.data
    })
    this.getByKey('user.initPassword').then(response => {
      this.initPassword = response.data
    })
  },
  methods: {
    inputSelect(){
      this.$refs.form.validateField('deptId');
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.userList = response.data
        this.total = response.total
        this.loading = false
      })
    },
    /** 转换机构数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.deptId,
        label: node.name,
        children: node.children
      }
    },
    /** 查询机构名称下拉树结构 */
    getDeptTree() {
      deptTree().then(response => {
        if (response.data && response.data.length > 0) {
          this.deptOptions = this.handleTree(response.data, 'deptId', 'parentId', 'children', response.data[0].parentId)
        } else {
          this.deptOption = []
        }
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.deptId
      this.queryParams.current = 1
      this.getList()
    },
    // 用户状态修改
    handleStatusChange(row) {
      const text = row.status === '0' ? this.$t('role.enable') : this.$t('role.outable')
      this.$confirm(this.$t('role.enterwant') + text + '""' + row.userName + this.$t('role.wantRole'), this.$t('warning'), {
        confirmButtonText: this.$t('submitText'),
        cancelButtonText: this.$t('cancelText'),
        type: 'warning'
      }).then(function() {
        return changeStatus(row.id, row.status)
      }).then(() => {
        this.msgSuccess(text + this.$t('success'))
      }).catch(function() {
        row.status = row.status === '0' ? '1' : '0'
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        deptId: undefined,
        deptName: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phone: undefined,
        email: undefined,
        sex: undefined,
        status: '0',
        remarks: undefined,
        newPassword: undefined,
        roles: []
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getDeptTree()
      getUser().then(response => {
        this.roleOptions = response.data.extend
        this.open = true
        this.title = this.$t('profile.add')
        this.form.password = this.initPassword
      })
    },
    /** 修改按钮操作 */
    handleEdit(row) {
      this.reset()
      this.getDeptTree()
      const id = row.id || this.ids
      getUser(id).then(response => {
        this.form = response.data.result
        this.roleOptions = response.data.extend
        this.form.roles = response.data.result.roles
        this.open = true
        this.title = this.$t('profile.change')
        this.form.password = ''
      })
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.reset()
      this.resetStatus = true
      this.resetId = row.id
      // this.$prompt(this.$t('profile.pleaseInput') + row.userName + this.$t('profile.deNewPaw'), this.$t('tip'), {
      //   confirmButtonText: this.$t('submitText'),
      //   cancelButtonText: this.$t('cancelText'),
      //   closeOnClickModal: false,
      //   closeOnHashChange: false,
      //   closeOnPressEscape: false
      // }).then(({ value }) => {
      //   resetPwd(row.id, value).then(response => {
      //     if (response.code === 0) {
      //       this.msgSuccess(this.$t('profile.changePswRight') + value)
      //     } else {
      //       this.msgError(response.msg)
      //     }
      //   })
      // }).catch(() => {})
    },
    /** 重置密码按钮操作 */
    handleResetPwdSure() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          resetPwd(this.resetId, this.form.newPassword).then(response => {
            if (response.code === 0) {
              this.resetStatus = false
              this.msgSuccess(this.$t('profile.changePswRight') + this.form.newPassword)
            } else {
              this.msgError(response.msg)
            }
          })
        }
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const getNameById = (deptId, deptOptions) => {
            for (let i = 0; i < deptOptions.length; i++) {
              if (deptOptions[i].deptId === deptId) {
                return deptOptions[i].name
              }
              if (deptOptions[i].children) {
                return getNameById(deptId, deptOptions[i].children)
              }
            }
            return ''
          }
          this.form.deptName = getNameById(this.form.deptId, this.deptOptions)
          if (this.form.id !== undefined) {
            editUser(this.form).then(response => {
              if (response.code === 0) {
                this.msgSuccess(this.$t('loginLog.changeSuccess'))
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          } else {
            addUser(this.form).then(response => {
              if (response.code === 0) {
                this.msgSuccess(this.$t('addSuccess'))
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDel(row) {
      const ids = row.id || this.ids
      this.$confirm(this.$t('profile.deleteUserNumber') + ids + this.$t('equipment.deleteEquipment2'), this.$t('warning'), {
        confirmButtonText: this.$t('submitText'),
        cancelButtonText: this.$t('cancelText'),
        type: 'warning'
      }).then(function() {
        return delUser(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('deleteSuccess'))
      }).catch(function() {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      if (this.ids.length === 0) {
        this.msgWarning(this.$t('equipment.equipmentInput'))
        return
      }
      const queryParams = this.queryParams
      this.$confirm(this.$t('profile.exportUserData'), this.$t('warning'), {
        confirmButtonText: this.$t('submitText'),
        cancelButtonText: this.$t('cancelText'),
        type: 'warning'
      }).then(() => {
        return exportUser(queryParams,this.ids)
      }).then(response => {
        this.download(response.data)
      }).catch(function() {
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = this.$t('profile.exportUser')
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.data)
      })
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.data, this.$t('elButton.importResult'), { dangerouslyUseHTMLString: true })
      this.getList()
    },
    handleFileError(err, file, fileList) {
      this.msgError(err)
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    }
  }
}
</script>
<style scoped>

</style>
